package com.sjy.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.Map;
@Component
public class SpringContextUtil implements BeanFactoryAware, ApplicationContextAware {

    public static DefaultListableBeanFactory listableBeanFactory;


    private static ApplicationContext applicationContext;
    @Override
    public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException {
        listableBeanFactory = (DefaultListableBeanFactory) beanFactory;
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> void registerSingleton(Class<T> type) {
        T obj = listableBeanFactory.createBean(type);
        String beanName = beanName(type.getName());
        listableBeanFactory.registerSingleton(beanName, obj);
    }

    public static void destroy(String className) {
        String beanName = beanName(className);
        listableBeanFactory.destroySingleton(beanName);
    }

    public static String beanName(String className){
        String[] path = className.split("\\.");
        String beanName = path[path.length - 1];
        return Character.toLowerCase(beanName.charAt(0)) + beanName.substring(1);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name){
        try{
            return (T) listableBeanFactory.getBean(name);
        }catch (NoSuchBeanDefinitionException e){

        }
        return null;
    }

    public static <T> T getBean(Class<T> type) {
        try {
            return listableBeanFactory.getBean(type);
        } catch (NoSuchBeanDefinitionException e) {

        }
        return null;
    }

    public static <T> Map<String, T> getBeans(Class<T> type) {
        try {
            return listableBeanFactory.getBeansOfType(type);
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return null;
    }
}

